<template>
    <div>
        <el-upload
            action=""
            class="avatar-uploader"
            :show-file-list="false"
            list-type="picture-card"
            :before-upload="beforeAvatarUpload"
            :http-request="upload"
            accept=".jpg,.png"
        >
            <!-- action="http://localhost:10009/pbFile/importFile"
            :headers="{ 'x-token': token }" -->
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>

<script>
  const path = process.env.VUE_APP_BASE_API;
  export default {
    name: "Avatar",
    props: {
      imageUrl:{
        type: String,
        default: ""
      },
      compressSize: {
        type: Number,
        default: 256, // 256KB 超出后执行压缩
      },
      maxSize: {
        type: Number,
        default: 512 , // 512KB 超出后执行报错
      },
      maxWH: {
        type: Number,
        default: 1920, // 图片长宽上限
      },
    },
    data() {
      return {
        token:  localStorage.getItem('Xdh_token')||""
      };
    },
    computed: {
      // ...mapGetters("user", ["userInfo", "token"]),
    },
    mounted () {
      setTimeout(() => {
      }, 1000);
    },
    methods: {
      beforeAvatarUpload(file) {
        console.log('file', file)
        const isRightSize = file.size / 1024< this.maxSize;
        if (!isRightSize) {
          // this.$message.error('文件大小不能超过 '+this.maxSize+'KB!');
          // return false
        }
        return true
      },
      // 上传
      async upload(params) {
        const file = params.file,
            fileType = file.type,
            isImage = fileType.indexOf("image") != -1,
            isLt2M = file.size / 1024 / 1024 < 2;
        // 这⾥常规检验，看项⽬需求⽽定
        if (!isImage) {
          this.$message.error("只能上传图⽚格式png、jpg、gif!");
          return;
        }
        // if (!isLt2M) {
        //   this.$message.error("只能上传图⽚⼤⼩⼩于2M");
        //   return;
        // }
        // 根据后台需求数据格式
        const form = new FormData();
        // ⽂件对象
        form.append("file", file);

        // const params = new FormData([param.file])
        console.log(form)
        this.$axios.importFile(form).then((res)=>{
          if (res.success) {
            this.$emit("change", res.data)
          }
        })
      },
    }
  }
</script>

<style scoped>

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        /* width: 178px;
        height: 178px; */
        /* line-height: 178px; */
        text-align: center;
    }
    .avatar {
        width: 148px;
        height: 148px;
        display: block;
    }

</style>
